package com.naiterui.ehp.bs.weixin.controller.openapi;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.naiterui.common.redis.RedisUtil;
import com.naiterui.ehp.bp.support.advice.IgnoreResponseEntityWrap;
import com.naiterui.ehp.bs.weixin.constant.WeixinMaConstant;
import com.naiterui.ehp.bs.weixin.service.UserService;
import com.naiterui.ehp.bs.weixin.service.WechatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 微信openapi接口
 *
 * @author yangfuya
 * @version 1.0
 * @date 2021/6/1 10:07
 **/
@Slf4j
@RestController
@RequestMapping("openapi/wechat")
@RequiredArgsConstructor
public class WeChatController {

    private final WechatService wechatService;
    private final UserService userService;

    /**
     * 缓存锁有效期，10s
     */
    private static final int LOCK_TIME = 10;

    /**
     * 小程序事件推送
     *
     * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     * @param jsonBody  事件数据
     * @return success
     */
    @IgnoreResponseEntityWrap
    @RequestMapping("/event/push")
    public String eventPush(String signature, String timestamp, String nonce, String echostr, @RequestBody @Nullable String jsonBody) {
        log.info("小程序事件推送信息，signature：{}，timestamp：{}，nonce：{}，echostr：{}，jsonBody：{}", signature, timestamp, nonce, echostr, jsonBody);
        // 服务器token校验
        if (StrUtil.isAllNotBlank(signature, timestamp, nonce, echostr)) {
            return wechatService.checkToken(signature, timestamp, nonce, echostr);
        }
        if (StrUtil.isNotBlank(jsonBody)) {
            JSONObject jsonObject = JSONUtil.parseObj(jsonBody);

            String fromUser = jsonObject.getStr("FromUserName");
            String createTime = jsonObject.getStr("CreateTime");

            // 缓存请求key
            String lockKey = WeixinMaConstant.getWechatMaMessageLockKey(fromUser + "_" + createTime);
            Long lockResult = RedisUtil.valueOps().setNx(lockKey, fromUser);
            if (lockResult == 0) {
                log.info("重复消息请求，不再处理，请求信息:{}", jsonBody);
                return "success";
            }
            String msgType = jsonObject.getStr("MsgType");
            if (WeixinMaConstant.JsonMsgType.EVENT.equals(msgType)) {
                String event = jsonObject.getStr("Event");
                if (WeixinMaConstant.SUBSCRIBE_MSG_POPUP_EVENT.equals(event)) {
                    Object list = jsonObject.get("List");
                    userService.handleUserSubscribe(fromUser, list);
                }
            }
            //设置缓存失效时间  10s
            RedisUtil.keyOps().expire(lockKey, LOCK_TIME);
        }
        return "success";
    }

}
